/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import me.zhengjie.modules.system.domain.DisPartner;
import me.zhengjie.modules.system.domain.DisPartnerUser;
import me.zhengjie.modules.web.service.mybatisplus.IDisPartnerPlusService;
import me.zhengjie.modules.web.service.mybatisplus.IDisPartnerUserPlusService;
import me.zhengjie.utils.*;
import lombok.RequiredArgsConstructor;
import me.zhengjie.modules.system.repository.DisPartnerRepository;
import me.zhengjie.modules.system.service.DisPartnerService;
import me.zhengjie.modules.system.service.dto.DisPartnerDto;
import me.zhengjie.modules.system.service.dto.DisPartnerQueryCriteria;
import me.zhengjie.modules.system.service.mapstruct.DisPartnerMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import java.util.List;
import java.util.Map;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.LinkedHashMap;

/**
* @website https://el-admin.vip
* @description 服务实现
* @author 王宇
* @date 2023-12-29
**/
@Service
@RequiredArgsConstructor
public class DisPartnerServiceImpl implements DisPartnerService {

    private final DisPartnerRepository disPartnerRepository;
    private final DisPartnerMapper disPartnerMapper;

    @Autowired
    private IDisPartnerPlusService partnerPlusService;

    @Autowired
    private IDisPartnerUserPlusService partnerUserPlusService;

    @Override
    public Map<String,Object> queryAll(DisPartnerQueryCriteria criteria, Pageable pageable){
        Page<DisPartner> page = disPartnerRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(disPartnerMapper::toDto));
    }

    @Override
    public List<DisPartnerDto> queryAll(DisPartnerQueryCriteria criteria){
        return disPartnerMapper.toDto(disPartnerRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    @Transactional
    public DisPartnerDto findById(Long partnerId) {
        DisPartner disPartner = disPartnerRepository.findById(partnerId).orElseGet(DisPartner::new);
        ValidationUtil.isNull(disPartner.getPartnerId(),"DisPartner","partnerId",partnerId);
        return disPartnerMapper.toDto(disPartner);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public DisPartnerDto create(DisPartner resources) {
        Snowflake snowflake = IdUtil.createSnowflake(1, 1);
        resources.setPartnerId(snowflake.nextId()); 
        return disPartnerMapper.toDto(disPartnerRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(DisPartner resources) {
        DisPartner disPartner = disPartnerRepository.findById(resources.getPartnerId()).orElseGet(DisPartner::new);
        ValidationUtil.isNull( disPartner.getPartnerId(),"DisPartner","id",resources.getPartnerId());
        disPartner.copy(resources);
        disPartnerRepository.save(disPartner);
    }

    @Override
    public void deleteAll(Long[] ids) {
        for (Long partnerId : ids) {
            disPartnerRepository.deleteById(partnerId);
        }
    }

    @Override
    public void download(List<DisPartnerDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (DisPartnerDto disPartner : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("名称", disPartner.getPartnerName());
            map.put("星级", disPartner.getStarNum());
            map.put("创建时间", disPartner.getCreateTime());
            map.put("创建人", disPartner.getCreateUser());
            map.put("更新时间", disPartner.getUpdateTime());
            map.put("更新用户", disPartner.getUpdateUser());
            map.put("状态，0：无效，1：有效，-1：删除", disPartner.getPartnerStatus());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Override
    public String getIdentityName(String mobile) {
        if (StringUtils.isBlank(mobile)){
            return "";
        }
        LambdaQueryWrapper<DisPartner> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DisPartner::getMobile,mobile);
        List<DisPartner> list = partnerPlusService.list(wrapper);
        if (CollectionUtils.isNotEmpty(list)){
            return list.get(0).getPartnerName()+"管理员";
        }
        LambdaQueryWrapper<DisPartnerUser> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(DisPartnerUser::getMobile,mobile);
        List<DisPartnerUser> list1 = partnerUserPlusService.list(wrapper1);
        if (CollectionUtils.isEmpty(list1)){
            return "";
        }
        DisPartnerUser disPartnerUser = list1.get(0);
        DisPartnerDto partnerDto = findById(disPartnerUser.getPartnerId());
        return partnerDto.getPartnerName()+"成员";
    }
}